import urllib2
import cookielib
import urllib
from BeautifulSoup import BeautifulSoup
from getpass import getpass
import os
from datetime import datetime
from threading import Thread
import time
import re

def get_grade_page(_id, password):
    login_url = 'https://registration.boun.edu.tr/scripts/stuinflogin.asp'
    login_data = {'user_name':_id, 'user_pass':password}
    grade_url = 'http://registration.boun.edu.tr/scripts/stuinfgs.asp?donem=2012/2013-1'
    
    cookies = cookielib.CookieJar()
    opener = urllib2.build_opener(
        urllib2.HTTPRedirectHandler(),
        urllib2.HTTPHandler(debuglevel=0),
        urllib2.HTTPSHandler(debuglevel=0),
        urllib2.HTTPCookieProcessor(cookies))

    opener.addheaders = [
        ('User-Agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11'),
        ('Referer', 'http://registration.boun.edu.tr/studententry.htm'),
    ]

    opener.open(login_url, urllib.urlencode(login_data)) # login
    response = opener.open(grade_url)
    html = response.read()
    return html

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')   

def print_grades(_id, password):
    soup = BeautifulSoup(get_grade_page(_id, password), 
        convertEntities=BeautifulSoup.HTML_ENTITIES)
    table = soup('table')[1]
    clear_screen()

    num_grades = 0
    for record in table('tr')[1:]:
        code, name, credits, grade, repeat = record('td')
        print str(code.text), str(grade.text)
        if re.search(r'\w+', grade.text):
            num_grades += 1

    print '\nLast update ' + datetime.now().strftime('%H:%M:%S')
    print '\nPress enter to refresh' 

    return num_grades


def automatic_check(_id, password, interval):
    interval *= 60
    num_grades = 0
    while True:
        time.sleep(interval)
        new_num_grades = print_grades(_id, password)
        if num_grades != new_num_grades:
            print '\a'
            num_grades = new_num_grades

def main():
    _id = raw_input('Student ID: ')
    password = getpass('Password: ')
    
    while True:
        try:
            interval = int(raw_input('Automatic check interval (min): '))
            break
        except ValueError:
            print 'Please enter an integer!'

    Thread(target=automatic_check, args=(_id, password,interval)).start()

    while True:
        print_grades(_id, password)
        if raw_input() == 'q':
            break
    
if __name__ == '__main__':
    main()
